package com.ssh.demo.user.entity.dto;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import com.ssh.demo.user.entity.User;

public class UserQueryDTO {
	
	private String userName;
	private String password;
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	public static Specification<User> getSpecification(UserQueryDTO userQueryDTO) {
		
		Specification<User> spec = new Specification<User>() {

			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				
				if(null != userQueryDTO && !StringUtils.isEmpty(userQueryDTO.getUserName())) {
					Predicate p1 = cb.like(root.get("userName").as(String.class), "%"+userQueryDTO.getUserName()+"%");
					list.add(p1);
				}
				if(null != userQueryDTO && !StringUtils.isEmpty(userQueryDTO.getPassword())) {
					Predicate p2 = cb.like(root.get("password").as(String.class), "%"+userQueryDTO.getPassword()+"%");
					list.add(p2);
				 }
				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}
			
		};
		return spec;
	}
	

}
